package model

import "ginblog/utils/errmsg"

type Category struct {
	ID uint `gorm:"primary_key;auto_increment" json:"id"`
	Name string `gorm:"type:varchar(20);not null" json:"name"`
}

//查询categoryname是否已经存在
func CheckCategoryName(name string) int {
	var category Category
	db.Debug().Select("id").Where("name = ?", name).First(&category)
	if category.ID >=1 {
		return errmsg.ERROR_CATENAME_USED
	}
	return errmsg.SUCCESS

}

//新增category
func AddCategory(data *Category) int {
	err := db.Debug().Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//查询categorys
func GetCategorys(pageSize int, pageNum int) ([]Category, int) {
	var categorys []Category
	err := db.Debug().Limit(pageSize).Offset((pageNum - 1)*pageSize).Find(&categorys).Error
	if err != nil {
		return nil, errmsg.ERROR
	}
	return categorys, errmsg.SUCCESS
}

//根据id查询category
func GetCategoryById(id int) (Category, int) {
	var category Category
	err := db.Debug().Where("id = ?", id).First(&category).Error
	if err != nil {
		return category, errmsg.ERROR_CATE_NOT_EXIST
	}
	return category, errmsg.SUCCESS
}

//根据id删除用户
func DeleteCategoryById(id int) int {
	var category Category
	err := db.Debug().Where("id = ?", id).Delete(&category).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//编辑category
func EditCategiryById(id int, data Category) int {
	var category Category
	map1 := make(map[string]interface{})
	map1["name"] = data.Name
	category.Name = data.Name
	err := db.Debug().Model(&category).Where("id = ?", id).Update(map1).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}